package com.apex.lottery.service.impl;

import com.apex.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.apex.lottery.common.exception.ServiceException;
import com.apex.lottery.common.utils.*;
import com.apex.lottery.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.apex.lottery.common.utils.Constants.VERIFICATION_CODE_TEMPLATE_CODE;

/**
 * @ClassName VerificationCodeServiceImpl
 * @Description
 * @Author ZJX
 * @Date 2025/3/29 18:41
 * @Version 1.0
 **/
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {



    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
//        1. 验证手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

//        2. 生成验证码
        String code = CaptchaUtil.getCaptcha(6);
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        smsUtil.sendMessage(
                VERIFICATION_CODE_TEMPLATE_CODE,
                phoneNumber,
                JacksonUtil.writeValueAsString(map));

//        3. 缓存验证码
        redisUtil.set(Constants.VERIFICATION_CODE_PREFIX + phoneNumber, code, Constants.VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //        1. 验证手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

       return redisUtil.get(Constants.VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
